<?php

namespace Lib\Model;

use StdClass,
    Lib\Exception\DatasourceNotFoundException,
    Lib\Util\Util,
    Lib\Model\Model;

class Datasource {

    public static $configFilename = 'database.json';

    protected $config;
    protected $model;

    public function __construct(StdClass $config, Model $model) {
        $this->config = $config;
        $this->model  = $model;
    }

    public static function load($name, Model $model) {
        $config = self::loadConfig($name);

        $className = "Lib\\Model\\Datasource\\{$config->type}";
        $Datasource = new $className($config, $model);
        
        return $Datasource;
    }

    private static function loadConfig($name) {
        $cfg = json_decode(file_get_contents(DIR_CONFIG . DS . self::$configFilename));
        if (! isset($cfg->$name)) {
            throw new DatasourceNotFoundException("Datasource configuration \"{$name}\"");
        }
        
        return $cfg->$name;
    }

}